package com.king.designpatterns.七大原则.单一职责;

import com.king.designpatterns.BaseDao;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

/**
 * 用户数据访问
 *
 * @author king
 * @date 2020/9/28 13:50
 */
public class UserDao extends BaseDao {

    private static final Logger logger = LoggerFactory.getLogger(UserDao.class);

    /**
     * 返回所有用户
     */
    public List<User> getAllUser() {
        List<User> userList = new ArrayList<>();
        String sql = "SELECT * FROM userdetail";

        try {
            ResultSet rs = this.executeQuery(sql);
            while (rs.next()) {
                userList.add(new User(rs.getString("username"),
                        rs.getString("userpass"), rs.getInt("role")));
            }
        } catch (SQLException e) {
            logger.error(e.getLocalizedMessage());
        }finally {
            this.closeConnection();
        }

        return userList;
    }

    /**
     * 根据用户名查找用户
     */
    public User getUserByName(String name) {
        User user = null;
        String sql = "SELECT * FROM userdetail WHERE username=?";

        try {
            ResultSet rs = this.executeQuery(sql, new String[]{name});
            if (rs.next()){
                user = new User(rs.getString("username"), rs.getString("userpass"), rs.getInt("role"));
            }
        } catch (SQLException e){
            logger.error(e.getLocalizedMessage());
        }finally {
            this.closeConnection();
        }

        return user;
    }

    /**
     * 添加新用户
     */
    public boolean addUser(User user) {
        String sql = "INSERT INTO userdetail(username, userpass, role) VALUES (?, ?, ?)";
        boolean flag;

        try {
            flag = this.executeUpdate(sql, new String[] {user.getUsername(), user.getUserpass(), user.getRole() + ""});
        }finally {
            this.closeConnection();
        }

        return flag;
    }

}
